package ilearn.job.disserver.order.service;

import ilearn.job.disserver.order.entity.Orders;
import ilearn.job.disserver.order.repository.OrdersRepository;
import ilearn.job.disserver.sdk.account.AccountCache;
import ilearn.job.disserver.sdk.account.dto.AccountDTO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrdersService {

    @Resource
    private OrdersRepository ordersRepository;
    @Resource
    private AccountCache accountCache;

    public Orders add(String accId, String goods, String desc, BigDecimal amt){
        AccountDTO accountDTO = accountCache.getAccountById(Long.valueOf(accId),true);
        if (accountDTO == null || accountDTO.getId() == 0){
            throw new RuntimeException("账户不存在");
        }
        if (accountDTO.getAge() < 18 && goods.startsWith("Nan18")){
            throw new RuntimeException("18禁不允许未成年购买");
        }
        Orders orders = Orders.builder().accId(accId).goods(goods).desc(desc).amt(amt).build();
        ordersRepository.save(orders);
        return orders;
    }

    public List<Orders> getOrdersByAccId(String accId){
        AccountDTO accountDTO = accountCache.getAccountById(Long.valueOf(accId),true);
        if (accountDTO == null || accountDTO.getId() == 0){
            throw new RuntimeException("账户不存在");
        }
        return ordersRepository.findByAccId(accId);
    }
}
